package com.web.util;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DataSourceUtils {
    // 数据源
    private static DataSource dataSource;


    static {
        Properties properties = new Properties();
        try {
            // 读配置文件
            properties.load(DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 初始化数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException | SQLException e) {
            throw new RuntimeException("初始化数据源失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return 数据库连接对象
     * @throws SQLException 如果获取连接失败
     */
    public static Connection getConnection() {
        if (dataSource != null) {
            try {
                return dataSource.getConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
